package org.xgluo;

import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import org.w3c.dom.Document;
import org.xgluo.excle.WriteExcle;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;


/**
 * @author LXG
 * @program: XmlToXlsx
 * @name: ReadXml
 * @description: 读取Xml文件
 * @date 2024年11月27日 10:28
 */
public class StartParseXml {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    /*
     * @Description: 使用Xml解析器，解析传入的文件获取所有节点
     * @param url
     * @return void
     * @date 2024/11/28 10:23
     * @author LXG
     */
    public void parseXml(String url) {

        try {
            //获取Document对象
            Document decoument = getDecoument(url);
            WriteExcle writeExcle = new WriteExcle(url);
            writeExcle.writeSheet(decoument);
            writeExcle.writeWorkbookToFile();

            System.out.println("XML file created successfully");
        } catch (ParserConfigurationException e) {
            System.out.println("获取DocumentFactory对象失败");
            throw new RuntimeException(e);
        } catch (IOException e) {
            System.out.println("读取Xml文档失败");
            throw new RuntimeException(e);
        } catch (SAXException e) {
            System.out.println("解析Xml文档成Document对象失败");
            throw new RuntimeException(e);
        }
    }


    /*
     * @Description: 根据路径获取Document对象
     * @param url 文件路径
     * @return Document
     * @date 2024/12/2 10:00
     * @author LXG
     */
    public Document getDecoument(String url) throws ParserConfigurationException, IOException, SAXException {
        //获取一个文件解析器工厂
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = factory.newDocumentBuilder();
        return documentBuilder.parse(new File(url));
    }

}
